#!/usr/bin/env python3.9
# -*- encoding: utf-8 -*-
"""
@文件        :serializers.py
@说明        : 小程序通过序列化器验证参数过程，实现openid的获取与用户注册
@时间        :2022/12/01 19:55:10
@作者        :Mars
@版本        :1.0
"""

from rest_framework import serializers

from mars.apps.systems.models import WechatConfig as WeConfig
from mars.libs.wechat import WeChat
from mars.utils.db import auto_commit
from mars.utils.exceptions.enums import StatusCodeEnum
from mars.utils.exceptions.exceptions import APIException

from .models import OAuthMPUser, User
from .utils import Token


class MpUserLoginSerializer(serializers.Serializer):
    """注册序列化器"""

    # appid = serializers.CharField(label="小程序AppID", max_length=18, write_only=True)
    code = serializers.CharField(label="小程序Code码", max_length=32, write_only=True)
    nickname = serializers.CharField(
        label="昵称",
        max_length=32,
        write_only=True,
        trim_whitespace=True,
        required=False,
    )
    access = serializers.CharField(label="AccessToken", max_length=128, read_only=True)
    refresh = serializers.CharField(
        label="RefreshToken", max_length=128, read_only=True
    )

    def validate(self, attrs):
        # app_id = attrs["appid"]
        code = attrs["code"]

        # 根据app_id 获取小程序配置信息（将来最好从redis中获取）
        _mp_config = WeConfig.objects.first()

        if not _mp_config:
            raise APIException(StatusCodeEnum.NODATA_ERR)
        # 获取openid

        attrs["openid"] = WeChat().get_openid(code, _mp_config)
        return attrs

    def create(self, validated_data):
        with auto_commit():
            openid = validated_data["openid"]
            _mp_user = OAuthMPUser.objects.filter(openid=openid).first()

            if not _mp_user:
                # 不存在用户，则创建用户
                user = User.objects.create_user(openid, "", "123456")
                user.save()

                # 创建小程序登录关联用户
                _mp_user = OAuthMPUser(openid=openid, user_id=user.id)
                _mp_user.save()
            else:
                user = User.objects.filter(id=_mp_user.user_id).first()

        # 生成token
        return Token.get_token(user)
